package com.zj.leetcode.medium.listNode;

/**
 * @program: algorithm
 * @description: 两两交换链表中的节点
 * 24 swap-nodes-in-pairs
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class SwapNodesInPairs {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4,
                                        new ListNode(5, null)))));
        Solution solution = new SwapNodesInPairs().new Solution();

        System.out.println(solution.swapPairs(listNode));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    class Solution {
        public ListNode swapPairs(ListNode head) {
            int size = (int) this.size(head);

            if (size <= 1) {
                return head;
            }


            ListNode cur = head;
            head = head.next;
            ListNode front = null;
            while (cur != null) {
                if (cur.next != null) {
                    if (front != null) {
                        front.next = cur.next;
                    }
                    ListNode temp = cur.next;
                    cur.next = cur.next.next;
                    temp.next = cur;
                    front = cur;
                }
                cur = cur.next;
            }
            return head;
        }

        public long size(ListNode head) {
            long size = 0;
            ListNode cur = head;
            while (cur != null) {
                size++;
                cur = cur.next;
            }

            return size;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}